
let {vec3} = require('gl-matrix');

let tmpVec3 = vec3.create();

class Ray{
    constructor(origin,dir){
        this.origin = vec3.fromValues(origin[0],origin[1],origin[2]);
        this.dir = vec3.create();
        vec3.normalize(this.dir,dir);
    }

    distanceToPoint(point){
        vec3.sub(tmpVec3,point,this.origin);
        let dirDistance = vec3.dot(tmpVec3,this.dir);
        if (dirDistance < 0){
            return vec3.length(vec3.sub(tmpVec3,this.origin,point));
        }
        // 求出垂足
        vec3.scale(tmpVec3,this.dir,dirDistance);
        vec3.add(tmpVec3,this.origin,tmpVec3);

        vec3.sub(tmpVec3,tmpVec3,point);
        return vec3.length(tmpVec3);
    }
}

// let ray = new Ray(vec3.fromValues(0,0,0),vec3.fromValues(1,1,0));
// console.log(ray.distanceToPoint(vec3.fromValues(-2,0,0)));

module.exports = Ray;
